package com.ufo.store.management.ui.activity;

import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ufo.store.management.R;
import com.ufo.store.management.adapter.CalenderViewPagerAdapter;
import com.ufo.store.management.calendar.LunarCalendar;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.PayMaster;
import com.ufo.store.management.entity.PayMasterGroup;
import com.ufo.store.management.entity.SerializableList;
import com.ufo.store.management.ui.fragment.CalenderFragment;
import com.ufo.store.management.utils.ScreenUtil;
import com.ufo.store.management.utils.StatusBarUtil;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.view.ArcProgress;
import com.ufo.store.management.widget.dialog.CalendarDialog;
import com.ufo.store.management.widget.dialog.DeleteItemDialog;
import com.ufo.store.management.BarApplication;

import java.sql.Date;
import java.sql.Time;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2015/9/25 0025.
 */
public class PayMasterActivity extends BaseActivity {
    public static final String TAG = PayMasterActivity.class.getSimpleName();

    public static final int CALENDER_DAY_COUNT = 365;

    private AppBarLayout appBarLayout;
    private Toolbar toolBar;
    private CollapsingToolbarLayout coordinatorLayout;

    private ViewPager mCalenderViewPager = null;
    private CalenderViewPagerAdapter mCalenderAdapter = null;

    private TextView paymaster_tips_tv = null;
    private TextView mPayMasterDateTv = null;
    private TextView paymaster_datetime_tv = null;
    private TextView mPayMasterBlotoutTv = null;
    private TextView mPayMasterTotalTv = null;
    private LinearLayout paymaster_total_ll = null;
    private LinearLayout paymaster_blotout_ll = null;
    private ArcProgress mArcProgress = null;

    private int mReadIndex = 0;
    private Object mLock = new Object();
    private int mPosition = CALENDER_DAY_COUNT - 1;
    private String mSearchDate = null;
    private String mSearchDateZh = null;

    private List<PayMaster> mPayMasterInfoList = null;
    private List<PayMasterGroup> mPayMasterGroupInfoList = new ArrayList<PayMasterGroup>();

    private DeleteItemDialog mDeleteItemDialog;
    private LunarCalendar mLunarCalendar = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        StatusBarUtil.setStatusBarColor(this, R.color.app_key_color, true);
        toolBar= (Toolbar) findViewById(R.id.tool_bar);
        //这个属性必须在setSupportActionBar(toolbar)之前调用  
        toolBar.setTitle("");
        setSupportActionBar(toolBar);
        //设置导航Icon，必须在setSupportActionBar(toolbar)之后设置  
        toolBar.setOnMenuItemClickListener(onMenuItemClickListener);
        toolBar.setNavigationIcon(R.drawable.ic_back_light_selector);
        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAfterTransition();
            }
        });
    }

    private void initData() {
        mLunarCalendar = new LunarCalendar();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.paymaster_menu, menu);
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finishAfterTransition();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private Toolbar.OnMenuItemClickListener onMenuItemClickListener = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_calendar:
                    showCalendar();
//                    getPayMasterInfoList(true);
//                    mCalenderAdapter.setRefresh();
                    break;
                case R.id.action_search:
                    Intent toIntent = new Intent(PayMasterActivity.this, SearchSaleDetailActivity.class);
                    startActivity(toIntent);
                    break;
                case R.id.action_delete:
                    showDeleteItemDialog();
                    break;
            }
            return true;
        }
    };

    private void initView() {
        setContentView(R.layout.activity_paymaster);
        coordinatorLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        coordinatorLayout.setCollapsedTitleTextColor(Color.parseColor("#3c3c3c"));
        coordinatorLayout.setExpandedTitleColor(Color.parseColor("#5c5c5c"));
        appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
        appBarLayout.addOnOffsetChangedListener(onOffsetChangedListener);

        mArcProgress = (ArcProgress) findViewById(R.id.ap);
        paymaster_tips_tv = ((TextView) findViewById(R.id.paymaster_tips_tv));
        mPayMasterDateTv = ((TextView) findViewById(R.id.paymaster_date_tv));
        paymaster_datetime_tv = ((TextView) findViewById(R.id.paymaster_datetime_tv));
        mPayMasterTotalTv = ((TextView) findViewById(R.id.paymaster_total_tv));
        mPayMasterBlotoutTv = (TextView) findViewById(R.id.paymaster_blotout_tv) ;
        paymaster_total_ll = (LinearLayout) findViewById(R.id.paymaster_total_ll) ;
        paymaster_blotout_ll = (LinearLayout) findViewById(R.id.paymaster_blotout_ll) ;

        mCalenderViewPager = ((ViewPager) findViewById(R.id.viewpager));
        mCalenderViewPager.setOnPageChangeListener(new CalenderPageChangeListener());
        mCalenderAdapter = new CalenderViewPagerAdapter(getSupportFragmentManager());
        mCalenderViewPager.setAdapter(mCalenderAdapter);
        mCalenderViewPager.setCurrentItem(CALENDER_DAY_COUNT - 1);
        mCalenderViewPager.setOffscreenPageLimit(0);

        mCalenderAdapter.setCalenderClickListener(new CalenderFragment.CalenderClickListener() {
            @Override
            public void onAccountsNumberClick() {
                showPayListActivity();
            }
        });

        getPayMasterInfoList(true);
    }

    public void showDeleteItemDialog() {
        if (mDeleteItemDialog == null) {
            mDeleteItemDialog = new DeleteItemDialog(this);
            Window window = mDeleteItemDialog.getWindow(); //得到对话框
            window.setWindowAnimations(R.style.dialog_anim_center_style); //设置窗口弹出动画
        }
        mDeleteItemDialog.setTips(mSearchDate + "的营业记录吗");
        mDeleteItemDialog.setItemClickListener(new DeleteItemDialog.OnItemClick() {
            @Override
            public void onItemClick(int position) {
                if (position == 0) {
                    //取消
                } else if (position == 1) {
                    //确定
                    new DeletePayMasterInfoTask().execute();
                }
            }
        });
        mDeleteItemDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        mDeleteItemDialog.show();
    }

    private void showCalendar(){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, mPosition - (CALENDER_DAY_COUNT - 1));
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        new CalendarDialog(PayMasterActivity.this, year, month, day).setItemClickListener(new CalendarDialog.OnItemClick() {
            @Override
            public void onPositiveButtonClick(int dayOfMonth, int month, int year) {
                refreshViewPager(dayOfMonth - 1, month, year);
            }

            @Override
            public void onNegativeButtonClick() {

            }
        });
    }

    private void showPayListActivity() {
        if (mPayMasterInfoList != null) {
            Intent toIntent = new Intent(PayMasterActivity.this, PayListActivity.class);
            Bundle bundle = new Bundle();
            SerializableList p = new SerializableList();
            p.setmPayMasterGroupInfoList(mPayMasterGroupInfoList);
            bundle.putSerializable("PayMasterGroup", p);
            bundle.putString("Date", mSearchDate);
            toIntent.putExtras(bundle);
            startActivity(toIntent);
        }
    }

    private final class CalenderPageChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case 0:
                    getPayMasterInfoList(true);
                    break;
                case 1:
                    break;
                case 2:
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            mPosition = arg0;
        }
    }

    private void refreshViewPager(int dayIndex, int monthIndex , int yearIndex) {
        calcDateIndex(dayIndex, monthIndex, yearIndex);
    }

    private void calcDateIndex(int daySelect, int monthSelect, int yearSelect){
        //当前年月日
        Calendar cal1 = Calendar.getInstance();
        String date1 = cal1.get(Calendar.YEAR) + "-" + String.valueOf(cal1.get(Calendar.MONTH) + 1) + "-" + String.valueOf(cal1.get(Calendar.DAY_OF_MONTH)) + " 00:00:00";

        //目标年月日
        String date2 = yearSelect + "-" + String.valueOf(monthSelect + 1) + "-" + String.valueOf(daySelect + 1) + " 00:00:00";

        long days = 0;

        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            java.util.Date dateNow = df.parse(date1);
            java.util.Date dateSelected = df.parse(date2);
            long l = dateNow.getTime() - dateSelected.getTime();
            days = l / (24 * 60 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int index = CALENDER_DAY_COUNT - (int) days - 1;
        if (index >= 0 && index < CALENDER_DAY_COUNT)
            mCalenderViewPager.setCurrentItem(index);
    }

    private synchronized void getPayMasterInfoList(boolean headerOrFooter) {
        if (PayMasterActivity.this.isFinishing()) {
            return;
        }
        new GetPayMasterInfoListTask().execute();
    }

    private class GetPayMasterInfoListTask extends AsyncTask<Void, Void, List<PayMaster>> {
        public GetPayMasterInfoListTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<PayMaster> doInBackground(Void... params) {
            if (PayMasterActivity.this.isFinishing()) {
                return null;
            }
            mReadIndex = 0;
            List<PayMaster> result = new ArrayList<>();

            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_MONTH, mPosition - (CALENDER_DAY_COUNT - 1));
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            int day = cal.get(Calendar.DAY_OF_MONTH);

            Date date = new Date(year - 1900, month - 1, day);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            mSearchDate = format.format(date);
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日");
            mSearchDateZh = format1.format(date);
            if (BarApplication.getInstance().mDatabaseIsSqlServer)
                result = DatabaseManager.getPayMasterInfoListFromSqlServer(PayMasterActivity.this, 1, mSearchDate);
            else
                result = DatabaseManager.getPayMasterInfoListFromLocal(PayMasterActivity.this, 1, mSearchDate);
            mReadIndex = mReadIndex + result.size();
            return result;
        }

        @Override
        protected void onPostExecute(List<PayMaster> result) {
            super.onPostExecute(result);
            if (PayMasterActivity.this.isFinishing()) {
                return;
            }

            if (result != null) {
                synchronized (mLock) {
                    mPayMasterInfoList = result;
                    mPayMasterGroupInfoList = getListData(mPayMasterInfoList);
                    ArrayList<String> hourValueList = new ArrayList<String>();
                    ArrayList<String> scanValueList = new ArrayList<String>();
                    int groupSize = mPayMasterGroupInfoList.size();
                    for (int i = 0; i < groupSize; i++) {
                        int childSize = mPayMasterGroupInfoList.get(i).getChildList().size();
                        hourValueList.add(mPayMasterGroupInfoList.get(i).getGroupName());
                        scanValueList.add(String.valueOf(childSize));
                    }

                    float fBlotout = 0;
                    float fTotal = 0;
                    float fReceivable = 0;
                    for (int i = 0; i < mPayMasterInfoList.size(); i++) {
                        PayMaster payMaster = mPayMasterInfoList.get(i);
                        fBlotout = fBlotout + payMaster.payMasterBlotout;
                        fTotal = fTotal + payMaster.payMasterTotal;
                        fReceivable = fReceivable + payMaster.payMasterReceivable;
                    }

                    DecimalFormat decimalFormat = new DecimalFormat("##,###.00");
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.DAY_OF_MONTH, mPosition - (PayMasterActivity.CALENDER_DAY_COUNT - 1));
                    int way = cal.get(Calendar.DAY_OF_WEEK);
                    String mWay = null;
                    if (way == 1) {
                        mWay = "日";
                    } else if (way == 2) {
                        mWay = "一";
                    } else if (way == 3) {
                        mWay = "二";
                    } else if (way == 4) {
                        mWay = "三";
                    } else if (way == 5) {
                        mWay = "四";
                    } else if (way == 6) {
                        mWay = "五";
                    } else if (way == 7) {
                        mWay = "六";
                    }
//                    int year = cal.get(Calendar.YEAR);
//                    int month = cal.get(Calendar.MONTH) + 1;
//                    int day = cal.get(Calendar.DAY_OF_MONTH);
//                    String lunarDay = mLunarCalendar.getLunarDate(year, month, day, false);
                    mPayMasterDateTv.setText(mSearchDateZh);
                    paymaster_datetime_tv.setText(" 周" + mWay);
                    //paymaster_datetime_tv.setText(" 周" + mWay + lunarDay);
                    mPayMasterTotalTv.setText( decimalFormat.format(fReceivable) );
                    mPayMasterBlotoutTv.setText( decimalFormat.format(fBlotout));

                    mCalenderAdapter.setAccountsNumber(String.valueOf(mPayMasterInfoList.size()), hourValueList, scanValueList);

                    ValueAnimator animator = ValueAnimator.ofFloat(0, fReceivable);
                    animator.setDuration(1200);
                    animator.setInterpolator(new DecelerateInterpolator());
                    animator.start();
                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator valueAnimator) {
                            Float integer = (Float) valueAnimator.getAnimatedValue();
                            mArcProgress.setProgress(integer.intValue());
                        }
                    });
                }
            }
        }
    }

    private class DeletePayMasterInfoTask extends AsyncTask<Void, Void, String> {
        public DeletePayMasterInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            long row = -1;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                row = DatabaseManager.deletePayMasterInfoFromSqlServer(PayMasterActivity.this, mSearchDate);
            }
            return String.valueOf(row);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            getPayMasterInfoList(true);
        }
    }

    private List<PayMasterGroup> getListData(List<PayMaster> payMasterList) {
        List<PayMasterGroup> groupList = new ArrayList<PayMasterGroup>();
        Map<String, String> map = new HashMap<String, String>();
        for (PayMaster payMasterInfo : payMasterList) {
            Time time = payMasterInfo.payMasterOpertime;
            int hour = time.getHours();
            if (!map.containsKey(String.valueOf(hour))) {
                PayMasterGroup groupEntity = new PayMasterGroup();
                groupEntity.setGroupName(String.valueOf(hour));

                List<PayMaster> childList = new ArrayList<PayMaster>();
                childList.add(payMasterInfo);

                groupEntity.setChildList(childList);
                groupList.add(groupEntity);
                map.put(String.valueOf(hour), String.valueOf(hour));
            } else {
                for (PayMasterGroup groupEntity : groupList) {
                    if (groupEntity.getGroupName().equals(String.valueOf(hour))) {
                        List<PayMaster> childList = groupEntity.getChildList();
                        childList.add(payMasterInfo);
                    }
                }
            }
        }
        return groupList;
    }

    /**
     * @desc
     * @author taoli
     * @time 2017/10/10 0010
     * 0:EXPANDED(展开)   1:COLLAPSED(折叠)   2:INTERNEDIATE(中间)
     */
    private int state = 0;
    private AppBarLayout.OnOffsetChangedListener onOffsetChangedListener = new AppBarLayout.OnOffsetChangedListener() {
        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            mArcProgress.setTranslationX(-ScreenUtil.getScreenSize(getActivity())[0] * Math.abs(verticalOffset) / appBarLayout.getTotalScrollRange()/2 );
            mArcProgress.setTranslationY(-Utils.sp2px(getResources(),325) * Math.abs(verticalOffset) / appBarLayout.getTotalScrollRange()/2);
            mArcProgress.setAlpha(1.0f - (float)Math.abs(verticalOffset) / (float)appBarLayout.getTotalScrollRange());
            mArcProgress.setScaleX(1.0f - (float)Math.abs(verticalOffset) / (float)appBarLayout.getTotalScrollRange());
            mArcProgress.setScaleY(1.0f - (float)Math.abs(verticalOffset) / (float)appBarLayout.getTotalScrollRange());

            paymaster_tips_tv.setTranslationX(ScreenUtil.getScreenSize(getActivity())[0] * Math.abs(verticalOffset) / appBarLayout.getTotalScrollRange() /2);
            paymaster_tips_tv.setTranslationY(-Utils.sp2px(getResources(),325) * Math.abs(verticalOffset) / appBarLayout.getTotalScrollRange()/2);
            paymaster_tips_tv.setAlpha(1.0f - (float)Math.abs(verticalOffset) / (float)appBarLayout.getTotalScrollRange());

            paymaster_total_ll.setTranslationX(-ScreenUtil.getScreenSize(getActivity())[0] * Math.abs(verticalOffset) / appBarLayout.getTotalScrollRange() / 3.5f);
            paymaster_total_ll.setTranslationY(-Utils.sp2px(getResources(),325) * Math.abs(verticalOffset) / appBarLayout.getTotalScrollRange() / 3.0f );
            paymaster_total_ll.setScaleX(1.0f - (float)Math.abs(verticalOffset) / (float)appBarLayout.getTotalScrollRange() * 0.3f);
            paymaster_total_ll.setScaleY(1.0f - (float)Math.abs(verticalOffset) / (float)appBarLayout.getTotalScrollRange() * 0.3f);

            paymaster_blotout_ll.setTranslationX(ScreenUtil.getScreenSize(getActivity())[0] * Math.abs(verticalOffset) / appBarLayout.getTotalScrollRange() / 2.8f);
            paymaster_blotout_ll.setTranslationY(-Utils.sp2px(getResources(),325) * Math.abs(verticalOffset) / appBarLayout.getTotalScrollRange() / 2.2f );


            //i>=0  Toolbar全部显示
            if (verticalOffset == 0) {
                //修改状态标记为展开
                if (state != 0) {
                    state = 0;
                    //StatusBarUtil.setStatusBarColor(MemberEditActivity.this, R.color.transparent, false);
                }
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                //修改状态标记为折叠
                if (state != 1) {
                    state = 1;
                    //StatusBarUtil.StatusBarLightMode(MemberEditActivity.this, R.color.transparent, false);
                }
            } else {
                //修改状态标记为中间
                if (state != 2) {
                    state = 2;
                }
            }
        }
    };
}
